import React, { Component } from 'react';
import { StyleSheet, PixelRatio, DeviceEventEmitter, ToastAndroid, Text, View, Image, Dimensions, Platform, TouchableOpacity } from "react-native";
import { style } from '../../theme/style';
import { API, API_GENERATE } from '../../config/api';
import HTTP from '../../utils/http';
import { GLOBAL } from '../../config/global';
import { STORAGE_CONSTANT } from '../../config/storage';
import { Common } from '../../component/common/Common';
import StorageHelper from '../../utils/storageHelper';
import JsonUtils from '../../utils/JsonUtils';
import Upload from '../../utils/Upload';
import QuoteService from '../price/my-siter/_common/service.js';
var ImagePicker = require('react-native-image-picker');



const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;

//图片选择器参数设置
var imgOptions = {
	title: '请选择图片来源',
	cancelButtonTitle: '取消',
	takePhotoButtonTitle: '拍照',
	chooseFromLibraryButtonTitle: '相册图片',
	quality: 0.1,
	storageOptions: {
		skipBackup: true,
		path: 'images'
	}
};


var source = null;

class ImgLocal extends Component {
	constructor(props) {
		super(props);
	}
	render () {
		return (
			<Image style={styles.headImg} source={require('../../imgs/user-head.png')} />
		)
	}
}


export class UserInfo extends Component {

	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '个人资料',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../imgs/goBackEmpty.png')} />),
			headerStyle: {
				elevation: 0,
				backgroundColor: style.color.themeColor,
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};


	constructor(props) {
		super(props);
		this.state = {
			imgUrl: '',
		}
		this._changeLog = this._changeLog.bind(this);
		this._uploadImg = this._uploadImg.bind(this);
		this._changeImg = this._changeImg.bind(this);
		this.userInfo = {};
		this.szzz = ''; //所在组织
		this.sqzz = []; //所在组织
	}

	async	componentWillMount () {

		let account = null;
		await this._getUserInfo()
		try {
			account = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		} catch (error) {
			console.log(error);
		}
		account = JSON.parse(account);
		this.setState({
			saveInfo: account,
			fileId: account.avatar
		})



		// 获取头像接口
		if (this.state.saveInfo && this.state.saveInfo.avatarUrl) {
			this.setState({
				imgServer: this.state.saveInfo.avatarUrl,
			})
		} else if (this.state.saveInfo.avatar) {
			let headObj = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: this.state.saveInfo.avatar }, {
				rejectError: false, //是否将错误数据以reject的方式返回
				handerError: true //统一出错处理 通过toast提示
			}, 30000);
			if (headObj) {
				this.setState({
					imgServer: headObj.image,
				})
			}
		}
	}

	_getUserInfo = async () => {
		//获取用户信息
		let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		if (userInfo) {
			this.userInfo = JSON.parse(userInfo);
		}

		if (this.userInfo.corpInfoTOs) {
			let reselt = '';
			this.userInfo.corpInfoTOs.forEach((item, index) => {
				reselt += item.corpName + (index != this.userInfo.corpInfoTOs.length - 1 ? ',' : '');
			})
			this.sqzz = reselt;
		}
		this.szzz = this.userInfo.corpName;
	}



	async	componentWillUnmount () {
		DeviceEventEmitter.emit('getImgUrl', { imgUrl: this.state.imgUrl, fileId: this.state.fileId });
	}

	_changeLog () {
		ImagePicker.showImagePicker(imgOptions, (response) => {

			if (response.didCancel) {
				console.log('用户取消了选择！');
			}
			else if (response.error) {
				console.log("ImagePicker发生错误：" + response.error);
			}
			else {
				source = { uri: response.uri };
				this._uploadImg(source);
			}
		});
	}

	async _uploadImg (imgUrl) {
		let uploadImgObj = {
			imgUrl,
			url: API_GENERATE(API.IMG_UPLOAD),
		}
		let responseData = await Upload.uploadImg(uploadImgObj);
		if (responseData) {
			let headObj = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: responseData.fileId }, null, 30000);
			if (headObj) {
				this.setState({
					headImg: { uri: headObj.image }
				})
			} else {
				this.setState({
					ls: true
				})
			}
			// this.setState({
			// 	imgUrl: responseData.filePath
			// })
			this._changeImg(responseData.fileId, this.state.imgUrl);
		}
	}


	async	_changeImg (fileId, imgUrl) {
		const requestObj = {};
		requestObj.fileId = fileId;
		HTTP.POST(API_GENERATE(API.CHANGE_LOG), requestObj).then((Result) => {
			StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY).then((res) => {
				let resData = JsonUtils.stringToJson(res);
				resData.avatarUrl = imgUrl;
				resData.avatar = fileId;
				StorageHelper.set(STORAGE_CONSTANT.USER_INFO_KEY, JsonUtils.jsonToString(resData));
			})
			if (Platform.OS === 'android') {
				ToastAndroid.show(Result, ToastAndroid.LONG);
			}
			this.setState({
				imgServer: source.uri,
				fileId: fileId
			});
		})
	}

	render () {
		const { params } = this.props.navigation.state;
		let defaultImg = require('../../imgs/user-head.png');
		let uriImg = { uri: this.state.imgServer };
		let { saveInfo } = this.state;
		let { userTeamList, bizLineNameList } = saveInfo || {};
		return (
			<View style={styles.container}>
				<View style={[styles.listBox, styles.listBoxActive]}>
					<View style={[styles.list, styles.listActiveTe]} >
						<Text style={styles.listLeft}>头像</Text>
						<TouchableOpacity onPress={this._changeLog} activeOpacity={1}>
							<Image style={styles.headImg} source={this.state.imgServer ? (this.state.imgDefault ? defaultImg : uriImg) : defaultImg}
								onError={(e) => {
									this.setState({ imgDefault: true })
								}} />
						</TouchableOpacity>
					</View>
					<View style={styles.list} >
						<Text style={styles.listLeft}>姓名</Text>
						<Text style={styles.listRight}>{params.userName || '匿名'}</Text>
					</View>
					<View style={styles.list} >
						<Text style={styles.listLeft}>性别</Text>
						<Text style={styles.listRight}>{params.sexName || '无'}</Text>
					</View>
					{/* <View style={styles.list} >
						<Text style={styles.listLeft}>职称</Text>
						<Text style={styles.listRight}>无</Text>
					</View> 
					<View style={styles.list} >
						<Text style={styles.listLeft}>产品线</Text>
						<Text style={styles.listRight}>{params.organName || '无'}</Text>
					</View>*/}
					<View style={[styles.listTow]} >
						<Text style={styles.listLeft} numberOfLines={1}>产品线</Text>
						<View style={[styles.listRight, styles.listRightMore]}>
							<Text style={styles.listRight}>
								{bizLineNameList && bizLineNameList.map((item, index) => {
									if (index < bizLineNameList.length - 1) {
										return `${item}、`;
									} else {
										return item;
									}
								})}
							</Text>
						</View>
					</View>
					<View style={[styles.listTow]} >
						<Text style={styles.listLeft} numberOfLines={1}>产品组</Text>
						<View style={[styles.listRight, styles.listRightMore]}>
							<Text style={styles.listRight}>
								{userTeamList && userTeamList.map((item, index) => {
									if (index < userTeamList.length - 1) {
										return `${item.teamName}、`;
									} else {
										return item.teamName;
									}
								})}
							</Text>
						</View>
					</View>
					<View style={styles.list} >
						<Text style={styles.listLeft}>所在组织</Text>
						<View style={styles.listRight}>
							<Text style={styles.listRight}>{this.szzz || '无'}</Text>
						</View>
					</View>
					{/* <View style={styles.list} >
						<Text style={styles.listLeft}>授权组织</Text>
						<View style={styles.listRight}>
							<Text style={styles.listRight}>{this.sqzz || '无'}</Text>
						</View>
					</View> */}
					<View style={[styles.listTow]} >
						<Text style={styles.listLeft} numberOfLines={1}>授权组织</Text>
						<View style={[styles.listRight, styles.listRightMore]}>
							<Text style={styles.listRight}>
								{this.userInfo.corpInfoTOs && this.userInfo.corpInfoTOs.map((item, index) => {
									if (index < this.userInfo.corpInfoTOs.length - 1) {
										return `${item.corpName}、`;
									} else {
										return item.corpName;
									}
								})}
							</Text>
						</View>
					</View>
					<View style={styles.list} >
						<Text style={styles.listLeft}>手机号</Text>
						<View style={styles.listRight}>
							<Text style={styles.listRight}>{params.mobileNo || '无'}</Text>
						</View>
					</View>
					<View style={[styles.list, styles.listActive]} >
						<Text style={styles.listLeft} numberOfLines={1}>邮箱</Text>
						<View style={styles.listRight}>
							<Text style={styles.listRight} numberOfLines={1}>{params.email || '无'}</Text>
						</View>
					</View>
				</View>
			</View >
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#FAFBFD',
	},
	headBox: {
		width: 375 * scale,
		height: 117 * scale
	},
	backgroundImage: {
		width: 375 * scale,
		height: 117 * scale,
	},
	listBoxActive: {
		marginTop: 12 * scale,
	},
	listBox: {
		backgroundColor: '#fff',
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale
	},
	list: {
		flexDirection: 'row',
		alignItems: 'center',
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border,
		height: 52 * scale
	},
	listTow: {
		flexDirection: 'row',
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border,
		minHeight: 20 * scale,
		paddingTop: 16 * scale,
		paddingBottom: 16 * scale
	},
	listActive: {
		borderBottomWidth: 0,
	},
	listActiveTe: {
		height: 68 * scale
	},
	listLeft: {
		flex: 1,
		fontSize: 14 * scale,
		color: '#404040'
	},
	listRight: {
		paddingRight: 7 * scale,
		flexDirection: 'row',
		alignItems: 'center',
	},
	listRightMore: {
		width: 250 * scale,
		flexWrap: 'wrap',
		flexDirection: 'row',
		justifyContent: 'flex-end'
	},
	listRightText: {
		color: '#8B8B8B',
		fontSize: 14 * scale,
		marginHorizontal: 5,
		flexShrink: 1,
		width: 250 * scale,
		textAlign: 'right'
	},
	listRightImg: {
		width: 6 * scale,
		height: 11 * scale,
	},
	headImg: {
		height: 42 * scale,
		width: 42 * scale,
		borderRadius: 21 * scale,
	}
})